package com.kalvan.admin.remoteserver;

import com.kalvan.commons.db.system.mapper.DictMapper;
import com.kalvan.commons.db.system.mapper.LogMapper;
import com.kalvan.commons.db.system.model.Dict;
import com.kalvan.commons.db.system.model.Log;
import com.kalvan.core.utils.BeanUtils;
import com.kalvan.remoteserver.bean.req.LogDto;
import com.kalvan.remoteserver.bean.res.DictDto;
import com.kalvan.remoteserver.iface.IBaseRemote;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenliang
 */
@Service
public class BaseServer implements IBaseRemote {

    @Autowired
    DictMapper dictMapper;

    @Autowired
    LogMapper logMapper;

    @Override
    public Map<String, DictDto> getDictMap(String dictType) {
        Example example = new Example(Dict.class);
        Example.Criteria cr = example.createCriteria();
        cr.andCondition("dict_type = ", dictType);
        //TODO 可使用select_disable 来禁用
        example.setOrderByClause(" priority asc");
        List<Dict> dicts = dictMapper.selectByExample(example);
        Map<String, DictDto> allDict = new HashMap<>(dicts.size());
        for (Dict dict : dicts) {
            allDict.put(dict.getDictKey(), BeanUtils.newAndCopy(dict, DictDto.class));
        }
        return allDict;
    }

    @Override
    @Async
    public void insertLog(LogDto logDto) {
        Log logBill = BeanUtils.newAndCopy(logDto, Log.class);
        if (logBill == null) {
            return ;
        }
        if (StringUtils.isBlank(logBill.getLogOldDetail())) {
            logBill.setLogOldDetail(null);
        }
        if (StringUtils.isBlank(logBill.getLogDetail())) {
            logBill.setLogDetail(null);
        }
        logMapper.insertSelective(logBill);
    }
}
